package com.ht.shop.controller;

import com.alibaba.druid.util.StringUtils;
import com.ht.shop.annotations.RequestMapping;

import com.ht.shop.exceptions.MyBaseException;

import com.ht.shop.pojo.TbUser;
import com.ht.shop.service.UserService;
import com.ht.shop.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RequestMapping("/user")
public class UserController {
    private UserService userService = new UserServiceImpl();

    @RequestMapping("logout")
    public String logOut(HttpServletRequest req, HttpServletResponse resp) {
        req.getSession().invalidate();

        return "redirect:/index.jsp";

    }

    /**
     * 登录
     * @param req
     * @param resp
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String savecode = (String)req.getSession().getAttribute("code");
        if (StringUtils.isEmpty(code)|| !code.equalsIgnoreCase(savecode)){

            resp.setContentType("text/html;charset=utf-8");

            return "验证码错误";
        }
        try {
            TbUser user = userService.login(username, password);
            if (user == null) {
                resp.setContentType("text/html;charset=utf-8");

                return "用户名或密码错误";
            }
            req.getSession().setAttribute("loginUser",user);
            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
           return  "redirect:/error/error.jsp";

        }
    }

    /**
     * 注册
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping("/register")
    public String register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            TbUser user = new TbUser();
            Map<String, String[]> parameterMap = req.getParameterMap();
            BeanUtils.populate(user,parameterMap);

            String repeatPassword = req.getParameter("repeatpassword");
            if (StringUtils.isEmpty(repeatPassword)||!repeatPassword.equals(user.getPassword())) {
                req.setAttribute("meg","两次输入的密码不一致");

                return "forward:/error/fail.jsp";
            }
            userService.addUser(user);
            return "redirect:/registerSuccess.jsp";
        } catch (MyBaseException e) {
            e.printStackTrace();
            req.getSession().setAttribute("msg",e.getMessage());
            return "redirect:/error/fail.jsp";

        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/error/fail.jsp";
        }
    }
}
